<template>
  <div>
    <div class="product-window" style="z-index:100;border-radius:0;" :class="selectShow ? 'on' : ''">
      <div class="textpic acea-row row-between-wrapper">
        <div class="pictrue">
          <img :src="present.image" class="image" @click="previewImg(present.image)"/>
        </div>
        <div class="text">
          <div class="line3">{{ present.storeName }}</div>
          <div class="money font-color-red">
            ￥
            <span class="num">{{ present.price }}</span>
            <!-- <span class="stock" v-if="textInfo.type != 'relation'">库存: {{ present.stock }}</span> -->
          </div>
        </div>
        <div 
          class="iconfont icon-guanbi" 
          @click="closeSelect" 
          style="width: 40px;height: 40px;text-align: center;line-height: 40px;"
        ></div>
      </div>
      <div class="productWinList">
        <div class="item" v-for="(item, indexw) in attr.productAttr" :key="indexw">
          <div class="title">{{ item.attrName||'' }}</div>
          <div class="listn acea-row row-middle">
            <div
              class="itemn"
              :class="{ 'selected': item.index === indexn,'disable':itemn.check}"
              v-for="(itemn, indexn) in item.attrValue" 
              v-if="item.attrValue"
              @click="tapAttr(indexw, indexn,itemn.check)"
              :key="indexn"
            >{{ itemn.attr }}
            </div>
            <div v-if="item.sku" class="itemn">
              {{item.sku}}
            </div>
          </div>
        </div>
      </div>
      <div class="product_cart">
        <div class="title">数量</div>
        <div class="carnum acea-row row-left">
          <div class="item reduce" :class="present.cart_num <= 1 ? 'on' : ''" @click="CartNumDes">-</div>
          <div class="item num">{{ present.cart_num }}</div>
          <div
            class="item plus on" 
            v-if="receiptGoods == 1"
          >+</div>
          <div 
            v-if="receiptGoods == 0"
            class="item plus"
            @click="CartNumAdd"
          >+</div>
        </div>
      </div>
      <div class="product-window_bottom">
        <button @tap="presentType" class="button">{{textInfo.text}}</button>
      </div>
    </div>
    
    <div class="mask" @touchmove.prevent :hidden="!selectShow" @click="closeSelect"></div>
  </div>
</template>
<script>
export default {
  props: ["selectShow","attributeInfo","textInfo"],
  data: function() {
    return {
      indexw: -1,
      indexn: -1,
      receiptGoods:0,
      present:{
        image:"",
        storeName:"",
        price:"",//当前商品价格
        stock:"",//当前库存
        unique:"",//当前规格
        cart_num: 1,//当前数量
        unselected:[],//没选规格名称
        gaugeLength:0,//判断有几个规格没选
      },
      attr: {
        cartAttr: false,
        productAttr: [],
        productSelect: {
          unique:""
        }
      },
      attrValue: "",
    };
  },
  watch: {
    // 监听页面数据初始化默认值
    attributeInfo(){
      // if(this.present.unique){
      //   return
      // }
      this.present.image = this.attributeInfo.storeInfo.image
      this.present.price = this.attributeInfo.storeInfo.price
      this.present.stock = this.attributeInfo.storeInfo.stock
      this.present.storeName = this.attributeInfo.storeInfo.storeName
      this.present.cart_num = 1
      this.present.unique = ""
      this.attr.productAttr = this.attributeInfo.productAttr || []
      this.present.gaugeLength = this.attr.productAttr && this.attr.productAttr.length
      this.present.unselected = []
      if(this.attr.productAttr){
        this.attr.productAttr.forEach((data,index) => {
          this.present.unselected.push(data.attrName);
        });
      }
      this.defaultAttributes()
    },
  },
  mounted: function() {
  },
  onUnload() {
    this.attr = {}
  },
  methods: {
    // 点击组件按钮
    presentType(){
      this.$emit("presentType",this.textInfo.text);
    },
    // 关闭组件
    closeSelect: function() {
      this.$emit('closeSelect',false)
    },
    CartNumDes: function() {
      this.ChangeCartNum(false)
    },
    CartNumAdd: function() {
      this.ChangeCartNum(1)
    },
    defaultAttributes(){ 
      let productAttr = this.attr.productAttr
      let isStock = true
      if(productAttr.length === 1){
		  this.currentClick({indexw: 0, indexn: 0})
        /* productAttr[0].attrValue.forEach((data,index) => {
          let stock = this.attributeInfo.productValue[data.attr].stock
          if( parseFloat(stock) > 0 && isStock){
            isStock = false
            this.currentClick({indexw: 0, indexn: index})
          }
        }); */
      }else if(productAttr.length === 2){
		  this.currentClick({indexw: 0, indexn: 0})
		  this.currentClick({indexw: 1, indexn: 0})
        /* for(var i=0;i<productAttr[0].attrValue.length;i++){
          productAttr[1].attrValue.forEach((data,index) => {
            let value = []
            value.push(productAttr[0].attrValueArr[i]);
            value.push(data.attr);
            let tvalue = value.join(",")
            for(var key in this.attributeInfo.productValue){
              if(key==tvalue){
                let stock = this.attributeInfo.productValue[tvalue].stock
                if( parseFloat(stock) > 0 && isStock){
                  isStock = false
                  this.currentClick({indexw: 0, indexn: i})
                  this.currentClick({indexw: 1, indexn: index})
                  return
                }
              }
            }
            value = value.reverse().join(",")
            if(this.attributeInfo.productValue[value]){
              let stock = this.attributeInfo.productValue[value].stock
              if( parseFloat(stock) > 0 && isStock){
                isStock = false
                this.currentClick({indexw: 0, indexn: i})
                this.currentClick({indexw: 1, indexn: index})
                return
              }
            }
          });
        } */
      }
    },
    // 点击规格
    tapAttr(indexw, indexn, check) {
      if(check){
        return
      }
      console.log(indexw, indexn,"------------------------tapAttr(indexw, indexn)");
      this.indexw = indexw;
      this.indexn = indexn;
      if(this.attr.productAttr[indexw].index == indexn){
        // this.$emit("currentClick", );
        this.currentClick({ indexw: indexw, indexn: -1 })
      }else{
        // this.$emit("currentClick", { indexw: indexw, indexn: indexn });
        this.currentClick({ indexw: indexw, indexn: indexn })
      } 
    },
    
    //预览选择的图片
    previewImg:function(e){
      console.log("预览的图片信息",e)
      var imgUrl = e; //获取当前点击的图片
      wx.previewImage({
        current: imgUrl, //当前图片地址
        // urls: imgArr,  //所有要预览的图片的地址集合数组形式
        urls: [imgUrl], //一张图写法
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    },
    currentClick(even){
      // console.log(even,"------------------currentClick(even)")
      let variable = JSON.parse(JSON.stringify(this.attr));
      variable.productAttr[even.indexw].index = even.indexn
      let length = variable.productAttr.length
      if( variable &&  length == 1){
      }else if(variable &&  length == 2){
        let exist = []
        let unselected = []
        variable.productAttr.forEach((data,index) => {
          if(data.index==-1 || !data.index && data.index != 0){
            unselected.push(data.attrName)
          }
          for(var i=0;i<data.attrValue.length;i++){
            if(index != even.indexw){
              if(even.indexn>-1){
                let resist = variable.productAttr[even.indexw].attrValue[even.indexn].attr
                for(var key in this.attributeInfo.productValue){
                  if(key.indexOf(resist) != -1){
                    if( key.indexOf(data.attrValue[i].attr) > -1 && key.indexOf(resist) > -1 ){
                      exist.push(data.attrValue[i].attr);
                    }
                  }
                }
              }
            }
          }
        });
        this.present.unselected = unselected
        console.log(exist,"--------------有货的",even.indexw)
        variable.productAttr.forEach((data,index) => {
          if(index != even.indexw && even.indexn>-1){
            for(var i=0;i<data.attrValue.length;i++){
              let resist = variable.productAttr[index].attrValue[i].attr
              if( exist.indexOf(resist) < 0 ){
                variable.productAttr[index].attrValue[i].check = true
              }else{
                variable.productAttr[index].attrValue[i].check = false
              }
            }
          }
        });
      }
      // 判断选择几个
      let isAll = []
      variable.productAttr.forEach((data,index) => {
        for(var i=0;i<data.attrValue.length;i++){
          if(variable.productAttr[index].index == i){
            isAll.push({w:index,n:i});
          }
        }
      });
      // 都选中了
      if(variable.productAttr.length ==isAll.length){
        console.log("都选中了",isAll)
        this.present.gaugeLength = 0
        let value = this
        .getCheckedValue(even.indexw,even.indexn)
        .join(",");
        for(var key in this.attributeInfo.productValue){
          console.log(value," this.ChangeAttr(value)-------------112")
          if(key==value){
            console.log(value," this.ChangeAttr(value)-------------112")
            this.ChangeAttr(value)
          }
        }
      }else if(isAll.length == 1){
        this.present.image = this.attributeInfo.storeInfo.image
        this.present.price = this.attributeInfo.storeInfo.price
        this.present.stock = this.attributeInfo.storeInfo.stock
        this.$set(this, "attrValue", "");
        this.$set(this, "attrTxt", "请选择");
        console.log("选了1个",isAll)
        this.present.gaugeLength = 1
        let exist = []
        let ifexist = false
        variable.productAttr.forEach((data,index) => {
          for(var i=0;i<data.attrValue.length;i++){
            if(index == even.indexw && even.indexw!=isAll[0].w){
              ifexist = true
              // 取消了还有一个选中
              let resist =  variable.productAttr[isAll[0].w].attrValue[isAll[0].n].attr
              for(var key in this.attributeInfo.productValue){
                if(key.indexOf(resist) != -1){
                  if( key.indexOf(data.attrValue[i].attr) > -1 && key.indexOf(resist) > -1 ){
                    exist.push(data.attrValue[i].attr);
                  }
                }
              }
            }
          }
        });
        if(ifexist){
          variable.productAttr.forEach((data,index) => {
            if(index != even.indexw && even.indexn>-1){
              for(var i=0;i<data.attrValue.length;i++){
                let resist = variable.productAttr[index].attrValue[i].attr
                if( exist.indexOf(resist) < 0 ){
                  variable.productAttr[index].attrValue[i].check = true
                }else{
                  variable.productAttr[index].attrValue[i].check = false
                }
              }
            }
            if(index == isAll[0].w){
              // 只选择一个同行都改为可选
              for(var i=0;i<data.attrValue.length;i++){
                variable.productAttr[index].attrValue[i].check = false
              }
            }
          });
        }
      }else if(isAll.length == 0){
        this.$set(this, "attrValue", "");
        this.present.gaugeLength = 2
        this.present.image = this.attributeInfo.storeInfo.image
        this.present.price = this.attributeInfo.storeInfo.price
        this.present.stock = this.attributeInfo.storeInfo.stock
        this.$set(this, "attrTxt", "请选择");
        variable.productAttr.forEach((data,index) => {
          for(var i=0;i<data.attrValue.length;i++){
            variable.productAttr[index].attrValue[i].check = false
          }
        });
      }
      this.attr = variable
    },

    //获取被选中属性；
    getCheckedValue: function(indexw,indexn) {
      let productAttr = JSON.parse(JSON.stringify(this.attr.productAttr));
      productAttr[indexw].index = indexn
      let value = [];
      for (let i = 0; i < productAttr.length; i++) {
        for (let j = 0; j < productAttr[i].attrValueArr.length; j++) {
          if (productAttr[i].index === j) {
            value.push(productAttr[i].attrValueArr[j]);
          }
        }
      }
      for(var key in this.attributeInfo.productValue){
        if(key==value){
          console.log(value,"---------------------111value")
          return value;
        }
      }
      value = value.reverse()
      console.log(value,"---------------------222value")
      return value;
    },
    //选择属性；
    ChangeAttr(res) {
      console.log(res,"---------------------参数")
      let productSelectValue =this.attributeInfo.productValue[res];
      if (productSelectValue) {
        this.present.image = productSelectValue.image
        this.present.price = productSelectValue.price
        this.present.stock = productSelectValue.stock
        this.present.unique = productSelectValue.unique
        this.present.cart_num = 1
        this.$set(this, "attrValue", res);
        this.$set(this, "attrTxt", "已选择");
      } else {
        this.$set(this.attr.productSelect, "image", this.attributeInfo.storeInfo.image);
        this.$set(this.attr.productSelect, "price", this.attributeInfo.storeInfo.price);
        this.$set(this.attr.productSelect, "stock", 0);
        this.$set(this.attr.productSelect, "unique", "");
        this.$set(this.attr.productSelect, "cart_num", 0);
        this.$set(this, "attrValue", "");
        this.$set(this, "attrTxt", "请选择");
        wx.showToast({ title: "暂时无货", icon: "none", duration: 1500 });
      }
    },
    // 数量选择
    ChangeCartNum: function(changeValue) {
      // 判断是不是拼团的
      if(this.textInfo.type === "group") {
        this.present.cart_num = 1
        this.$dialog.message("每人每次限购1" + this.attributeInfo.storeInfo.unitName);
      
      // 判断是不是秒杀的
      } else if (this.textInfo.type === "spike"){
        if (changeValue) {
          if (this.present.cart_num < this.present.stock) {
            this.present.cart_num++;
          }
        } else {
          if (this.present.cart_num > 1) {
            this.present.cart_num--;
          }
        }
      } else if (this.textInfo.type === "relation") {
        if (changeValue) {
          this.present.cart_num++;
        } else {
          if (this.present.cart_num > 1) {
            this.present.cart_num--;
          }
        }
      }
      // //changeValue:是否 加|减
      // //获取当前变动属性
      // let productSelect = this.attributeInfo.productValue[this.attrValue];
      // //如果没有属性,赋值给商品默认库存
      // if (productSelect === undefined && !this.attributeInfo.productAttr.length) {
      //   productSelect = this.attributeInfo.storeInfo;
      // }
      // //无属性值即库存为0；不存在加减；
      // if (productSelect === undefined) return;
      // let stock = productSelect.stock || 0;
      // let num = this.present;
      // if (changeValue) {
      //   num.cart_num++;
      //   if (num.cart_num > stock) {
      //     this.present.cart_num = stock
      //   } else {
      //     this.present.cart_num = num.cart_num
      //   }
      // } else {
      //   num.cart_num--;
      //   this.present.cart_num = num.cart_num
      //   if (num.cart_num < 1) {
      //     this.present.cart_num = 1
      //   }
      // }
    },
  }
};
</script>

<style lang="less" scoped>
  .selected{
    color: #ff563d !important;
    background-color: #FFF2F0 !important;
    border: 2rpx solid #ff563d!important;
  }
  .disable{
    color:#BDBDBD!important;
    background-color: #F7F7F7;
    border: 2rpx dashed #DADADA!important;
  }
  .product-window_bottom{
    height: 150rpx;
    width: 690rpx;
    position: fixed;
    bottom: 0;
    background-color: #ffffff;
    z-index: 100;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 30rpx;
    .button{
      height: 90rpx;
      background-color: #FF563D;
      color: #ffffff;
      font-size: 28rpx;
      width: 690rpx;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 45rpx;
    }
  }
  .product_cart {
    margin-top: 0.36rem;
    padding: 0 0.3rem;
  }
  .product_cart .title {
    font-size: 0.28rem;
    color: #999999;
  }
  .product_cart .carnum {
    height: 0.54rem;
    margin-top: 0.24rem;
  }
  .product_cart .carnum .item {
    border: 1px solid #a4a4a4;
    width: 0.84rem;
    text-align: center;
    height: 100%;
    line-height: 0.54rem;
    color: #a4a4a4;
    font-size: 0.45rem;
  }
  .product_cart .carnum .reduce {
    border-right: 0;
    border-radius: 0.06rem 0 0 0.06rem;
    line-height: 0.48rem;
  }
  .product_cart .carnum .reduce.on {
    border-color: #e3e3e3;
    color: #dedede;
  }
  .product_cart .carnum .plus {
    border-left: 0;
    border-radius: 0 0.06rem 0.06rem 0;
    line-height: 0.46rem;
  }
  .product_cart .carnum .plus.on {
    border-color: #e3e3e3;
    color: #dedede;
  }
  .product_cart .carnum .num {
    color: #333333;
    font-size: 0.28rem;
  }
</style>